<?php

namespace App\Http\Controllers\Miniprograme;

use App\Helpers\NewBaseData;
use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Models\CouponLog;
use App\Models\User;
use Illuminate\Http\Request;
use Modules\Manager\Entities\Department;

class ApiController extends ComController
{
    use ResponseData,NewBaseData;
//    获取用户openid
    public function sessionKey(Request $request){
        $session = $this->miniProgram->auth->session($request->code);
        $shop = $request->input('source','总店');
        $source_id = $request->input('source_id','1');
        if(isset($session['session_key'])){
            $user = $this->getUser($session['openid']);
            if($user){
                $user->session_key=$session;
                $user->token = $this->token($user);
                return $this->success($user);
            }else{
                $data['openid'] = $session['openid'];
                $data['role']=0;
                $data['source'] = $shop;
                $data['source_id'] = $this->searchLastDepartment($source_id);
                //无主账户
                $account =User::query()->create($data);
                $account->session_key=$session;
                $account->token = $this->token($account);
                return $this->success($account);
            }
        }else{
            return $this->failed('获取用户信息失败,请联系管理员',201);
        }
    }
    // 获取最后一次分配的店铺
    protected function searchLastDepartment($source_id){
        // 总店的ID现在是1
        if($source_id==1){
            // 获取允许分配的门店数据列表
            $list = Department::query()->where('order_auto_assign',1)->orderBy('id')->pluck('id')->toArray();
            if (count($list) > 0) {
                $res = $list[0];
                // 最后一个已分配的部门ID
                $value = User::query()->latest()->value('source_id');
                if($value){
                    $key = array_search($value, $list);
                    if (($key+1) >= count($list)) {
                        $res = $list[0];
                    } else {
                        $res = $list[$key+1];
                    }
                }
                // if($request->filled('openid')){
                //     $user = User::query()->where('openid',$request->openid)->first();
                //     if($user){
                //         $user->department = $res;
                //         $user->save();
                //     }
                // }
                // LeaseChangeLog::query()->create(['department'=>$res,'order_sn'=>$order_sn]);
                return $res;
            } else {
                return $source_id;
            }
        }else{
            return $source_id;
        }

    }
    //获取用户身份令牌
    protected function token($user){
        //撤销用户所有令牌
        $user->tokens()->delete();
        //重新发布令牌
        return $user->createToken('user_login:'.$user->id)->plainTextToken;

    }
    //用户授权登录
    public function authLogin(CouponLog $couponLog,Request $request){
            $user = $this->miniProgram->encryptor->decryptData($request->session_key , $request->iv, $request->encryptedData);
            $data = $this->handleData($user,$request->openid);
            User::updateOrCreate(['openid'=>$request->openid],$data);
            //领取优惠券 - 不自动领取了，2025.08.11改为手动领取
            // $coupon = $this->getCoupon($request->openid);
            // if(!$coupon){
            //     $map = [];
            //     $coupon = $this->get_coupon(1);
            //     $map['name']= $coupon->name;
            //     $user = $this->getUser($request->openid);
            //     $map['nick_name'] = $user->nickName;
            //     $map['price'] = $coupon->price;
            //     $map['openid']  = $request->openid;
            //     $couponLog->create($map);
            // }
            return $this->success($data);
    }
    //获取用户信息
    public function memberInfo(Request $request){
        return $this->success($this->getUser($request->openid??''));
    }
    protected function getUser($openid){
        return User::where('openid',$openid)->with('customer','company')->first();
    }
    //更新用户信息
    public function update(Request $request){
        $data = User::where('openid',$request->openid)->first();
        $data->update($request->all());
        return $this->success('更新成功');

    }
    //整理数据
    protected function handleData($userInfo,$openid)
    {
        $arr  = $this->get_invite_num();
        $data = [
            'username'=>'小程序用户',
            'password'=>encrypt('123456'),
            'phone'=>$userInfo['phoneNumber'],
            'invite_num'=>$this->get_radom($arr),//邀请码
            //'nickName'=>$userInfo['nickName'],//$data['nickname'],
            //'avatarUrl'=>$userInfo['avatarUrl'],//$data['headimgurl'],
            //'country'=>$userInfo['country'],//$data['headimgurl'],
            //'province'=>$userInfo['province'],//$data['headimgurl'],
            //'city'=>$userInfo['city'],//$data['headimgurl'],
            //'gender'=>$userInfo['gender'],//$data['headimgurl'],
            'openid'=>$openid,
        ];
        if(isset($userInfo['unionId'])){
            $data['unionid']    = $userInfo['unionId'];
        }
        return $data;
    }
    //获取用户随机数组
    protected function get_invite_num(){
        return User::pluck('invite_num')->toArray();
    }
    //递归获取随机数
    protected function get_radom($arr){
        $number = $this->get_number();

        if(in_array($number,$arr)){
            $this->get_radom($arr);
        }else{
            return $number;
        }
    }
    //获取随机数
    protected function get_number(){
        return random_int(1000000,999999999);
    }

}
